package com.buaa.divinationmaster.interpretation;

import android.content.Context;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 上下文分析器
 * 分析用户问题的类别、情感基调和上下文信息
 * 用于提供更精准和个性化的解读
 * 
 * 核心功能：
 * - 问题类别识别
 * - 情感基调分析
 * - 关键词提取
 * - 上下文理解
 */
public class ContextAnalyzer {
    
    private static final String TAG = "ContextAnalyzer";
    
    /**
     * 问题类别枚举
     */
    public enum QuestionCategory {
        LOVE_RELATIONSHIP("感情关系", Arrays.asList("感情", "爱情", "恋爱", "婚姻", "分手", "复合", "喜欢", "暗恋", "表白", "结婚", "离婚", "伴侣", "男友", "女友", "老公", "老婆")),
        CAREER_WORK("事业工作", Arrays.asList("工作", "事业", "职业", "上班", "跳槽", "升职", "加薪", "同事", "老板", "面试", "辞职", "创业", "生意", "项目", "晋升")),
        HEALTH_WELLBEING("健康养生", Arrays.asList("健康", "身体", "生病", "医院", "治疗", "养生", "锻炼", "减肥", "疾病", "康复", "体重", "医生", "药物", "手术")),
        MONEY_FINANCE("金钱财务", Arrays.asList("钱", "财运", "投资", "理财", "股票", "房子", "买房", "贷款", "债务", "收入", "花钱", "存钱", "财务", "经济", "购买")),
        PERSONAL_GROWTH("个人成长", Arrays.asList("学习", "考试", "成长", "提升", "技能", "能力", "目标", "梦想", "未来", "规划", "发展", "进步", "修行", "智慧")),
        FAMILY_FRIENDS("家庭朋友", Arrays.asList("家人", "父母", "孩子", "朋友", "亲情", "友情", "家庭", "关系", "沟通", "矛盾", "和解", "理解", "支持")),
        GENERAL("综合其他", Arrays.asList());
        
        private final String name;
        private final List<String> keywords;
        
        QuestionCategory(String name, List<String> keywords) {
            this.name = name;
            this.keywords = keywords;
        }
        
        public String getName() { return name; }
        public List<String> getKeywords() { return keywords; }
    }
    
    /**
     * 情感基调枚举
     */
    public enum EmotionalTone {
        ANXIOUS("焦虑担心", Arrays.asList("担心", "焦虑", "害怕", "紧张", "不安", "忧虑", "恐惧", "慌张", "着急", "烦躁")),
        HOPEFUL("希望期待", Arrays.asList("希望", "期待", "想要", "渴望", "盼望", "愿望", "梦想", "期盼", "向往", "憧憬")),
        CONFUSED("困惑迷茫", Arrays.asList("困惑", "迷茫", "不知道", "纠结", "犹豫", "不确定", "疑惑", "茫然", "无所适从", "选择")),
        DETERMINED("坚定决心", Arrays.asList("决定", "坚定", "一定", "必须", "下定决心", "决心", "坚持", "执着", "毅力", "目标明确")),
        SEEKING_ADVICE("寻求建议", Arrays.asList("应该", "怎么办", "如何", "建议", "指导", "帮助", "意见", "方法", "策略", "怎样")),
        GRATEFUL("感激欣慰", Arrays.asList("感谢", "感激", "欣慰", "高兴", "开心", "满足", "庆幸", "幸福", "快乐", "满意")),
        NEUTRAL("中性平和", Arrays.asList());
        
        private final String name;
        private final List<String> indicators;
        
        EmotionalTone(String name, List<String> indicators) {
            this.name = name;
            this.indicators = indicators;
        }
        
        public String getName() { return name; }
        public List<String> getIndicators() { return indicators; }
    }
    
    /**
     * 问题紧急程度
     */
    public enum UrgencyLevel {
        IMMEDIATE("立即需要", Arrays.asList("紧急", "马上", "立刻", "现在", "急", "快", "赶紧", "尽快")),
        SOON("近期需要", Arrays.asList("最近", "这几天", "这周", "这个月", "不久", "很快", "近期", "短期")),
        FUTURE("未来规划", Arrays.asList("将来", "以后", "未来", "长远", "今后", "日后", "长期", "终生")),
        GENERAL("一般情况", Arrays.asList());
        
        private final String name;
        private final List<String> indicators;
        
        UrgencyLevel(String name, List<String> indicators) {
            this.name = name;
            this.indicators = indicators;
        }
        
        public String getName() { return name; }
        public List<String> getIndicators() { return indicators; }
    }
    
    /**
     * 问题上下文结果
     */
    public static class QuestionContext {
        private String originalQuestion;
        private QuestionCategory category;
        private EmotionalTone emotionalTone;
        private UrgencyLevel urgencyLevel;
        private List<String> extractedKeywords;
        private Map<String, Object> metadata;
        private float confidenceScore;
        
        public QuestionContext(String originalQuestion) {
            this.originalQuestion = originalQuestion;
            this.extractedKeywords = new ArrayList<>();
            this.metadata = new HashMap<>();
            this.confidenceScore = 0.0f;
        }
        
        // Getters and Setters
        public String getOriginalQuestion() { return originalQuestion; }
        
        public QuestionCategory getCategory() { return category; }
        public void setCategory(QuestionCategory category) { this.category = category; }
        
        public EmotionalTone getEmotionalTone() { return emotionalTone; }
        public void setEmotionalTone(EmotionalTone emotionalTone) { this.emotionalTone = emotionalTone; }
        
        public UrgencyLevel getUrgencyLevel() { return urgencyLevel; }
        public void setUrgencyLevel(UrgencyLevel urgencyLevel) { this.urgencyLevel = urgencyLevel; }
        
        public List<String> getExtractedKeywords() { return extractedKeywords; }
        public void addKeyword(String keyword) { this.extractedKeywords.add(keyword); }
        
        public Map<String, Object> getMetadata() { return metadata; }
        public void addMetadata(String key, Object value) { this.metadata.put(key, value); }
        
        public float getConfidenceScore() { return confidenceScore; }
        public void setConfidenceScore(float confidenceScore) { this.confidenceScore = confidenceScore; }
        
        /**
         * 获取分析摘要
         */
        public String getAnalysisSummary() {
            return String.format("类别: %s, 情感: %s, 紧急度: %s, 置信度: %.2f", 
                category.getName(), emotionalTone.getName(), urgencyLevel.getName(), confidenceScore);
        }
    }
    
    private Context context;
    private Map<String, Pattern> questionPatterns;
    private Map<String, Float> categoryWeights;
    
    public ContextAnalyzer(Context context) {
        this.context = context;
        initializePatterns();
        initializeCategoryWeights();
    }
    
    /**
     * 分析问题的上下文信息
     */
    public QuestionContext analyzeQuestion(String question) {
        if (question == null || question.trim().isEmpty()) {
            return createDefaultContext("", QuestionCategory.GENERAL, EmotionalTone.NEUTRAL);
        }
        
        QuestionContext context = new QuestionContext(question);
        
        // 1. 预处理问题文本
        String processedQuestion = preprocessQuestion(question);
        
        // 2. 分析问题类别
        QuestionCategory category = analyzeCategory(processedQuestion);
        context.setCategory(category);
        
        // 3. 分析情感基调
        EmotionalTone emotionalTone = analyzeEmotionalTone(processedQuestion);
        context.setEmotionalTone(emotionalTone);
        
        // 4. 分析紧急程度
        UrgencyLevel urgencyLevel = analyzeUrgencyLevel(processedQuestion);
        context.setUrgencyLevel(urgencyLevel);
        
        // 5. 提取关键词
        List<String> keywords = extractKeywords(processedQuestion, category);
        context.extractedKeywords.addAll(keywords);
        
        // 6. 计算置信度
        float confidence = calculateConfidence(context, processedQuestion);
        context.setConfidenceScore(confidence);
        
        // 7. 添加元数据
        addAnalysisMetadata(context, processedQuestion);
        
        return context;
    }
    
    /**
     * 预处理问题文本
     */
    private String preprocessQuestion(String question) {
        // 去除多余空格和特殊字符
        String processed = question.trim().replaceAll("\\s+", " ");
        
        // 转换为小写（用于关键词匹配）
        processed = processed.toLowerCase();
        
        // 去除标点符号（保留中文）
        processed = processed.replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9\\s]", "");
        
        return processed;
    }
    
    /**
     * 分析问题类别
     */
    private QuestionCategory analyzeCategory(String question) {
        Map<QuestionCategory, Integer> categoryScores = new HashMap<>();
        
        // 初始化分数
        for (QuestionCategory category : QuestionCategory.values()) {
            categoryScores.put(category, 0);
        }
        
        // 基于关键词匹配计算分数
        for (QuestionCategory category : QuestionCategory.values()) {
            for (String keyword : category.getKeywords()) {
                if (question.contains(keyword)) {
                    categoryScores.put(category, categoryScores.get(category) + 1);
                }
            }
        }
        
        // 基于模式匹配增加分数
        addPatternBasedScores(question, categoryScores);
        
        // 找到最高分的类别
        QuestionCategory bestCategory = QuestionCategory.GENERAL;
        int maxScore = 0;
        
        for (Map.Entry<QuestionCategory, Integer> entry : categoryScores.entrySet()) {
            if (entry.getValue() > maxScore) {
                maxScore = entry.getValue();
                bestCategory = entry.getKey();
            }
        }
        
        return bestCategory;
    }
    
    /**
     * 分析情感基调
     */
    private EmotionalTone analyzeEmotionalTone(String question) {
        Map<EmotionalTone, Integer> toneScores = new HashMap<>();
        
        // 初始化分数
        for (EmotionalTone tone : EmotionalTone.values()) {
            toneScores.put(tone, 0);
        }
        
        // 基于指示词匹配
        for (EmotionalTone tone : EmotionalTone.values()) {
            for (String indicator : tone.getIndicators()) {
                if (question.contains(indicator)) {
                    toneScores.put(tone, toneScores.get(tone) + 1);
                }
            }
        }
        
        // 基于问句模式判断
        if (question.contains("？") || question.contains("?") || question.contains("怎么")) {
            toneScores.put(EmotionalTone.SEEKING_ADVICE, toneScores.get(EmotionalTone.SEEKING_ADVICE) + 2);
        }
        
        if (question.contains("会不会") || question.contains("是否") || question.contains("能否")) {
            toneScores.put(EmotionalTone.CONFUSED, toneScores.get(EmotionalTone.CONFUSED) + 1);
        }
        
        // 找到最高分的情感基调
        EmotionalTone bestTone = EmotionalTone.NEUTRAL;
        int maxScore = 0;
        
        for (Map.Entry<EmotionalTone, Integer> entry : toneScores.entrySet()) {
            if (entry.getValue() > maxScore) {
                maxScore = entry.getValue();
                bestTone = entry.getKey();
            }
        }
        
        return bestTone;
    }
    
    /**
     * 分析紧急程度
     */
    private UrgencyLevel analyzeUrgencyLevel(String question) {
        for (UrgencyLevel level : UrgencyLevel.values()) {
            for (String indicator : level.getIndicators()) {
                if (question.contains(indicator)) {
                    return level;
                }
            }
        }
        
        return UrgencyLevel.GENERAL;
    }
    
    /**
     * 提取关键词
     */
    private List<String> extractKeywords(String question, QuestionCategory category) {
        List<String> keywords = new ArrayList<>();
        
        // 提取类别相关的关键词
        for (String keyword : category.getKeywords()) {
            if (question.contains(keyword)) {
                keywords.add(keyword);
            }
        }
        
        // 提取其他重要词汇
        String[] words = question.split("\\s+");
        for (String word : words) {
            if (word.length() > 1 && isImportantWord(word)) {
                keywords.add(word);
            }
        }
        
        return keywords;
    }
    
    /**
     * 计算分析置信度
     */
    private float calculateConfidence(QuestionContext context, String question) {
        float confidence = 0.0f;
        
        // 基于关键词匹配数量
        int keywordMatches = context.getExtractedKeywords().size();
        confidence += Math.min(keywordMatches * 0.1f, 0.5f);
        
        // 基于问题长度（更长的问题通常包含更多信息）
        int questionLength = question.length();
        if (questionLength > 10) {
            confidence += 0.2f;
        }
        if (questionLength > 30) {
            confidence += 0.1f;
        }
        
        // 基于类别的权重
        Float categoryWeight = categoryWeights.get(context.getCategory().getName());
        if (categoryWeight != null) {
            confidence += categoryWeight * 0.2f;
        }
        
        return Math.min(confidence, 1.0f);
    }
    
    /**
     * 添加分析元数据
     */
    private void addAnalysisMetadata(QuestionContext context, String question) {
        context.addMetadata("question_length", question.length());
        context.addMetadata("word_count", question.split("\\s+").length);
        context.addMetadata("has_question_mark", question.contains("？") || question.contains("?"));
        context.addMetadata("analysis_timestamp", System.currentTimeMillis());
        
        // 添加语言特征
        boolean hasTimeReference = containsTimeReference(question);
        context.addMetadata("has_time_reference", hasTimeReference);
        
        boolean hasPersonReference = containsPersonReference(question);
        context.addMetadata("has_person_reference", hasPersonReference);
    }
    
    /**
     * 基于模式匹配增加类别分数
     */
    private void addPatternBasedScores(String question, Map<QuestionCategory, Integer> scores) {
        // 感情类别的模式
        if (question.matches(".*和.*在一起.*") || question.matches(".*喜欢.*")) {
            scores.put(QuestionCategory.LOVE_RELATIONSHIP, scores.get(QuestionCategory.LOVE_RELATIONSHIP) + 2);
        }
        
        // 工作类别的模式
        if (question.matches(".*工作.*顺利.*") || question.matches(".*升职.*机会.*")) {
            scores.put(QuestionCategory.CAREER_WORK, scores.get(QuestionCategory.CAREER_WORK) + 2);
        }
        
        // 健康类别的模式
        if (question.matches(".*身体.*健康.*") || question.matches(".*病.*好.*")) {
            scores.put(QuestionCategory.HEALTH_WELLBEING, scores.get(QuestionCategory.HEALTH_WELLBEING) + 2);
        }
        
        // 财务类别的模式
        if (question.matches(".*赚钱.*") || question.matches(".*投资.*收益.*")) {
            scores.put(QuestionCategory.MONEY_FINANCE, scores.get(QuestionCategory.MONEY_FINANCE) + 2);
        }
    }
    
    /**
     * 判断是否为重要词汇
     */
    private boolean isImportantWord(String word) {
        // 过滤停止词和无意义词汇
        List<String> stopWords = Arrays.asList("的", "是", "在", "有", "和", "了", "我", "你", "他", "她", "它", "们");
        return !stopWords.contains(word) && word.matches("[\u4e00-\u9fa5]+");
    }
    
    /**
     * 检查是否包含时间引用
     */
    private boolean containsTimeReference(String question) {
        List<String> timeWords = Arrays.asList("今天", "明天", "昨天", "这周", "下周", "这个月", "下个月", "今年", "明年", "最近", "以后", "将来", "未来");
        for (String timeWord : timeWords) {
            if (question.contains(timeWord)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查是否包含人称引用
     */
    private boolean containsPersonReference(String question) {
        List<String> personWords = Arrays.asList("我", "你", "他", "她", "我们", "你们", "他们", "她们", "对方", "别人");
        for (String personWord : personWords) {
            if (question.contains(personWord)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 创建默认上下文
     */
    private QuestionContext createDefaultContext(String question, QuestionCategory category, EmotionalTone tone) {
        QuestionContext context = new QuestionContext(question);
        context.setCategory(category);
        context.setEmotionalTone(tone);
        context.setUrgencyLevel(UrgencyLevel.GENERAL);
        context.setConfidenceScore(0.1f);
        return context;
    }
    
    /**
     * 初始化问题模式
     */
    private void initializePatterns() {
        questionPatterns = new HashMap<>();
        
        // 感情相关模式
        questionPatterns.put("love_future", Pattern.compile(".*感情.*未来.*"));
        questionPatterns.put("love_current", Pattern.compile(".*现在.*感情.*"));
        questionPatterns.put("breakup", Pattern.compile(".*分手.*"));
        questionPatterns.put("reunion", Pattern.compile(".*复合.*"));
        
        // 工作相关模式
        questionPatterns.put("job_change", Pattern.compile(".*换工作.*|.*跳槽.*"));
        questionPatterns.put("promotion", Pattern.compile(".*升职.*|.*晋升.*"));
        questionPatterns.put("career_development", Pattern.compile(".*事业.*发展.*"));
        
        // 健康相关模式
        questionPatterns.put("health_condition", Pattern.compile(".*健康.*状况.*"));
        questionPatterns.put("illness_recovery", Pattern.compile(".*病.*恢复.*"));
        
        // 财务相关模式
        questionPatterns.put("money_luck", Pattern.compile(".*财运.*"));
        questionPatterns.put("investment", Pattern.compile(".*投资.*"));
        questionPatterns.put("business", Pattern.compile(".*生意.*"));
    }
    
    /**
     * 初始化类别权重
     */  
    private void initializeCategoryWeights() {
        categoryWeights = new HashMap<>();
        categoryWeights.put("感情关系", 1.0f);
        categoryWeights.put("事业工作", 0.9f);
        categoryWeights.put("健康养生", 0.8f);
        categoryWeights.put("金钱财务", 0.8f);
        categoryWeights.put("个人成长", 0.7f);
        categoryWeights.put("家庭朋友", 0.7f);
        categoryWeights.put("综合其他", 0.5f);
    }
    
    /**
     * 获取问题分析的详细信息（用于调试）
     */
    public String getDetailedAnalysis(QuestionContext context) {
        StringBuilder analysis = new StringBuilder();
        analysis.append("=== 问题分析详情 ===\n");
        analysis.append("原始问题: ").append(context.getOriginalQuestion()).append("\n");
        analysis.append("分析类别: ").append(context.getCategory().getName()).append("\n");
        analysis.append("情感基调: ").append(context.getEmotionalTone().getName()).append("\n");
        analysis.append("紧急程度: ").append(context.getUrgencyLevel().getName()).append("\n");
        analysis.append("提取关键词: ").append(String.join(", ", context.getExtractedKeywords())).append("\n");
        analysis.append("置信度: ").append(String.format("%.2f", context.getConfidenceScore())).append("\n");
        analysis.append("元数据: ").append(context.getMetadata().toString()).append("\n");
        
        return analysis.toString();
    }
}
